package com.atguigu.gulimall.gulimallseckkill.Service.Impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.mq.SecKillOrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRsepVo;
import com.atguigu.gulimall.gulimallseckkill.Feign.CouponFeignService;
import com.atguigu.gulimall.gulimallseckkill.Feign.ProductFeignService;
import com.atguigu.gulimall.gulimallseckkill.Service.SeckillService;
import com.atguigu.gulimall.gulimallseckkill.interceptor.LoginInterceptor;
import com.atguigu.gulimall.gulimallseckkill.to.SeckillSkuRedisTo;
import com.atguigu.gulimall.gulimallseckkill.vo.SeckillSesssionsWithSkus;
import com.atguigu.gulimall.gulimallseckkill.vo.SeckillSkuRelationEntity;
import com.atguigu.gulimall.gulimallseckkill.vo.SkuInfoVo;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * <p>Title: SeckillServiceImpl</p>
 * Description：
 * date：2020/7/6 17:33
 */
@Slf4j
@Service
public class SeckillServiceImpl implements SeckillService {
    @Autowired
    private CouponFeignService couponFeignService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    RedissonClient redissonClient;

    @Autowired
    private RabbitTemplate rabbitTemplate;
    private final String SESSIONS_CACHE_PREFIX = "seckill:sessions:";
    private final String SKUKILL_CACHE_PREFIX = "seckill:skus:";
    private final String SKU_STOCK_SEckill = "seckill:stock:";

    @Override
    public void uploadSeckillSkuLatest3Day() {
        //
        R lates3DaySession = couponFeignService.getLates3DaySession();
        if (lates3DaySession.getCode() == 0) {
            List<SeckillSesssionsWithSkus> sesssions = lates3DaySession.getData(new TypeReference<List<SeckillSesssionsWithSkus>>() {
            });
            //缓存活动信息
            saveSessionInfo(sesssions);
            //缓存活动的关联信息
            saveSessionSkuInfos(sesssions);
        }
    }

    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {
        //1.确定当前时间属于哪个秒杀场次
        long time = new Date().getTime();
        Set<String> keys = stringRedisTemplate.keys(SESSIONS_CACHE_PREFIX + "*");
        for (String key : keys) {
            String replace = key.replace(SESSIONS_CACHE_PREFIX, "");
            String[] s = replace.split("_");
            long start = Long.parseLong(s[0]);
            long end = Long.parseLong(s[1]);
            if (time >= start && time <= end) {
                //2.获取这个秒杀场次的所有商品信息
                List<String> range = stringRedisTemplate.opsForList().range(key, -100, 100);
                BoundHashOperations<String, String, String> hashOperations = stringRedisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                List<String> list = hashOperations.multiGet(range);
                if (list != null && list.size() > 0) {
                    List<SeckillSkuRedisTo> collect = list.stream().map(item -> {

                        SeckillSkuRedisTo seckillSkuRedisTo1 = JSON.parseObject(item.toString(), SeckillSkuRedisTo.class);
                        return seckillSkuRedisTo1;
                    }).collect(Collectors.toList());
                    return collect;
                }
                break;
            }
        }
        return null;
    }

    @Override
    public SeckillSkuRedisTo getSkuSeckillInfo(Long skuId) {
        //
        BoundHashOperations<String, String, String> hashOps =
                stringRedisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        Set<String> keys = hashOps.keys();
        if (keys != null && keys.size() > 0) {
            String regex = "\\d_" + skuId;
            for (String key : keys) {
                if (Pattern.matches(regex, key)) {
                    String json = hashOps.get(key);
                    SeckillSkuRedisTo seckillSkuRedisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);
                    Long startTime = seckillSkuRedisTo.getStartTime();
                    Long endTime = seckillSkuRedisTo.getEndTime();
                    long currentTime = new Date().getTime();
                    if (currentTime >= startTime && currentTime <= endTime) {

                    } else {
                        seckillSkuRedisTo.setRandomCode(null);
                    }
                    return seckillSkuRedisTo;
                }

            }
        }
        return null;
    }

    @Override
    public String kill(String killId, String key, Integer num) {
        MemberRsepVo memberRsepVo = LoginInterceptor.loginUser.get();


        BoundHashOperations<String, String, String> hashOps = stringRedisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        String json = hashOps.get(killId);
        if (StringUtils.isEmpty(json)) {
            return null;
        } else {
            SeckillSkuRedisTo seckillSkuRedisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);
            Long startTime = seckillSkuRedisTo.getStartTime();
            Long endTime = seckillSkuRedisTo.getEndTime();
            long time = new Date().getTime();
            long ttl = endTime - time;
            //校验时间合法性
            if (time >= startTime && time <= endTime) {
                //验证随机码和商品信息

                String randomCode = seckillSkuRedisTo.getRandomCode();
                String skuId = seckillSkuRedisTo.getPromotionSessionId() + "_" + seckillSkuRedisTo.getSkuId();
                if (randomCode.equals(key) && killId.equals(skuId)) {
                    //验证购买数量是否合理
                    BigDecimal seckillLimit = seckillSkuRedisTo.getSeckillLimit();
                    int i = seckillLimit.intValue();
                    if (num <= i) {
                        String redis = memberRsepVo.getId() + "_" + skuId;
                        Boolean b = stringRedisTemplate.opsForValue().setIfAbsent(redis, num.toString(), ttl, TimeUnit.MILLISECONDS);
                        if (b) {
                            //占位成功,从没买过,否则反之
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEckill + randomCode);
                            try {
                                boolean b1 = semaphore.tryAcquire(num, 100, TimeUnit.MILLISECONDS);
                                //秒杀成功
                                if (b1) {
                                    String timeId = IdWorker.getTimeId();
                                    SecKillOrderTo SecKillOrderTo = new SecKillOrderTo();
                                    SecKillOrderTo.setOrderSn(timeId);
                                    SecKillOrderTo.setMemberId(memberRsepVo.getId());
                                    SecKillOrderTo.setNum(num);
                                    SecKillOrderTo.setSeckillPrice(seckillSkuRedisTo.getSeckillPrice());
                                    SecKillOrderTo.setPromotionSessionId(seckillSkuRedisTo.getPromotionSessionId());
                                    SecKillOrderTo.setSkuId(seckillSkuRedisTo.getSkuId());

                                    rabbitTemplate.convertAndSend(
                                            "order.event.exchange"
                                            , "order.seckill.order", SecKillOrderTo);
                                    return timeId;
                                }
                                        return null;
                            } catch (InterruptedException e) {
                                return null;
                            }
                        } else {
                            return null;
                        }
                    }
                } else {
                    return null;
                }
            } else {
                return null;
            }

        }
        return "";
    }

    private void saveSessionInfo(List<SeckillSesssionsWithSkus> sesssions) {
        if (sesssions != null) {
            sesssions.stream().forEach(session -> {
                long startTime = session.getStartTime().getTime();
                long endTime = session.getEndTime().getTime();
                String key = SESSIONS_CACHE_PREFIX + startTime + "_" + endTime;
                Boolean b = stringRedisTemplate.hasKey(key);

                if (!b) {
                    List<String> collect = session.getRelationEntities().stream().map(item -> item.getPromotionSessionId() + "_" + item.getSkuId().toString()).collect(Collectors.toList());

                    stringRedisTemplate.opsForList().leftPushAll(key, collect);
                }

            });

        }

    }

    private void saveSessionSkuInfos(List<SeckillSesssionsWithSkus> sesssions) {
        if (sesssions != null) {
            sesssions.stream().forEach(session -> {
                //缓存商品信息
                BoundHashOperations<String, Object, Object> ops = stringRedisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                session.getRelationEntities().stream().forEach(seckillSkuRelationEntity -> {
                    String token = UUID.randomUUID().toString().replace("-", "");


                    if (!ops.hasKey(seckillSkuRelationEntity.getPromotionSessionId().toString() + "_" + seckillSkuRelationEntity.getSkuId().toString())) {
                        //sku基本数据
                        SeckillSkuRedisTo seckillSkuRedisTo = new SeckillSkuRedisTo();
                        //sku秒杀信息

                        R SkuInfo = productFeignService.info(seckillSkuRelationEntity.getSkuId());
                        if (SkuInfo.getCode() == 0) {
                            SkuInfoVo skuInfo = SkuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                            });
                            seckillSkuRedisTo.setSkuInfoVo(skuInfo);
                        }
                        BeanUtils.copyProperties(seckillSkuRelationEntity, seckillSkuRedisTo);
                        //3设置当前商品的秒杀时间信息
                        seckillSkuRedisTo.setStartTime(session.getStartTime().getTime());
                        seckillSkuRedisTo.setEndTime(session.getEndTime().getTime());
                        //4随机码
                        seckillSkuRedisTo.setRandomCode(token);

                        String jsonString = JSON.toJSONString(seckillSkuRedisTo);
                        ops.put(seckillSkuRelationEntity.getPromotionSessionId().toString() + "_" + seckillSkuRelationEntity.getSkuId().toString(), jsonString);

                        //5.使用库存作为信号量，可以限流
                        RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEckill + token);
                        BigDecimal seckillCount = seckillSkuRelationEntity.getSeckillCount();
                        semaphore.trySetPermits(seckillCount.intValue());
                    }

                });
            });
        }
    }

}
